package org.scohen.juploadr.app.scalers;

import java.awt.image.RenderedImage;
import java.awt.image.renderable.ParameterBlock;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.LinkedList;
import java.util.List;

import javax.media.jai.InterpolationBicubic2;
import javax.media.jai.JAI;
import javax.media.jai.RenderedOp;

import org.eclipse.swt.graphics.Point;
import org.scohen.juploadr.prefs.Configuration;

public class JAIScaler extends Scaler {
    private static final String[] JAI_JAR_FILES = { "jai_core.jar",
            "jai_codec.jar", "mlibwrapper_jai.jar" };
    
    public JAIScaler() {
        if (Configuration.isMac()) {
            // try to load JAI from the system directory
            File extDir = new File("/System/Library/Java/Extensions/");
            List<URL> jarUrls = new LinkedList<URL>();
            if (extDir.exists()) {
                for (int i = 0; i < JAI_JAR_FILES.length; i++) {
                    String jarFile = JAI_JAR_FILES[i];
                    File jar = new File(extDir, jarFile);
                    if (jar.exists()) {
                        try {
                            jarUrls.add(jar.toURL());
                        } catch (MalformedURLException e) {
                            // Don't really know how this can happen
                            e.printStackTrace();
                        }
                    }
                    
                    URLClassLoader.newInstance(jarUrls.toArray(new URL[jarUrls.size()]));
                }
            }
        }

    }

    public void doScale(File original, File scaled, Point newSize) {
        RenderedImage fullSize = JAI.create("fileload",original.getAbsolutePath());
        float scale = (float) newSize.x  / fullSize.getWidth();
        ParameterBlock pb = new ParameterBlock();
        pb.addSource(fullSize);
        pb.add(scale);
        pb.add(scale);
        pb.add(0.0F);
        pb.add(0.0F);
        pb.add(new InterpolationBicubic2(16));
        RenderedOp im = JAI.create("scale",pb,null);
        JAI.create("filestore",im,scaled.getAbsolutePath(),"JPEG",null);
    }

    public boolean isOptimal() {
         return false;
    }

}
